<template>
  <div class="editrole">
    <el-dialog :title="title" :visible="dialogFormVisible" @close="giveup">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          prop="name"
          label="角色名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="description"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="giveup">取 消</el-button>
        <el-button type="primary" @click="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleById, changeRole, getAllRole, addRole } from '@/api/setting'
export default {
  name: 'editrole',
  data () {
    //   重名查询
    let checkname = async (relues, value, callback) => {
      // 遍历得到所有的角色
      let res = await getAllRole()
      let list = res.data.rows
      //   是否存在同名,并且不是自己
      list.some(item => item.name == value && item.id != this.form.id)
        ? callback('该角色名已存在')
        : callback()
    }
    return {
      form: {},
      formLabelWidth: '120px',
      rules: {
        name: [
          { required: true, message: '角色名不能为空', trigger: 'blur' },
          { validator: checkname, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    currtentId: {
      type: String,
      default: ''
    },
    dialogFormVisible: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    async getRoleById (id) {
      let res = await getRoleById(id)
      this.form = res.data
    },
    // 点击确认
    primary () {
      // 做表单验证
      this.$refs.form.validate(async v => {
        if (v) {
          //   验证通过
          //   判断是新增还是编辑
          if (this.form.id) {
            await changeRole(this.form)
          } else {
            await addRole(this.form)
          }
          // 提交更跟新数据
          //   提交刷新页面通知
          this.$emit('updateMsg')
          //   提示用户
          this.$message.success('修改成功')
          // 提交关闭事件
          this.$emit('primaryClick')
        } else {
          // 不通过
        }
      })
    },
    giveup () {
      this.form = {}
      this.$refs.form.resetFields()
      this.$emit('giveupchange')
      // 重置表单，因为如果不重置表单，只是内容清空了，校验的提示还在
    }
  },
  computed: {
    title: function () {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  }
}
</script>

<style></style>
